﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utilities;

namespace ManageTicket.Human
{
    public partial class frmEmployee : frmBase
    {
        #region Contructor
        public frmEmployee()
        {
            InitializeComponent();
        }
        #endregion

        #region Variable
        ManageTicket.Library.Control.ExecuteControl exeCtrl;

        //permission
        bool bAdd = false;
        bool bEdit = false;
        bool bDelete = false;
        bool bCancel = false;
        bool bSave = false;
        bool bFunction = false;
        bool bView = false;
        bool bFind = false;
        bool bExport = false;
        bool bSendmail = false;
        bool bPrint = false;

        clsMethod4All objMethod = new clsMethod4All();
        ManageTicket.Library.Common.CommonFunction clsCommonFunc = new ManageTicket.Library.Common.CommonFunction();
        private Business.Employee boEmployee = new Business.Employee();

        private ArrayList arrDept = new ArrayList();
        TreeNode curNode;
        TreeNode SeleteNode;
        #endregion

        #region Event
        private void frmEmployee_Load(object sender, EventArgs e)
        {
            //execute control
            exeCtrl = new ManageTicket.Library.Control.ExecuteControl();
            exeCtrl.Dock = DockStyle.Fill;
            exeCtrl.lblDescription.Text = "Cập nhật danh sách nhân viên";
            pnlExe.Controls.Add(exeCtrl);

            //permission
            clsCommonFunc.GetPermission(ref bAdd, ref bEdit, ref bDelete, ref bCancel, ref bSave, ref bFunction, ref bView, ref bFind, ref bExport, ref bSendmail, ref bPrint, frmMain.CurrentUser.UserId, "FORM_14");
            
            //get code type
            clsCommonFunc.GetListCodeType(cboGender, "GENDER");
            clsCommonFunc.GetListCodeType(cboNationality, "NATION");
            clsCommonFunc.GetListCodeType(cboEducation, "EDU");
            clsCommonFunc.GetListCodeType(cboBank, "BANK");

            //get department
            BuildTree();

            //get position
            GetListPosition();

            //set status
            LoadStatusOnce();
        }

        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                ArrayList arrResult = new ArrayList();
                if (objMethod.IsInteger(txtSearch.Text))
                {
                    DataObjects.Employee oEmp = boEmployee.GetObjectByPK(txtSearch.Text);
                    if (oEmp != null)
                    {
                        arrResult.Add(oEmp);
                    }
                }
                else
                {
                    ArrayList arr1 = boEmployee.GetListQuickSearch(txtSearch.Text);
                    if (arr1 != null)
                    {
                        if (arr1.Count == 1)
                        {
                            arrResult.Add(arr1[0]);
                        }
                        else if (arr1.Count > 1)
                        {
                            frmQuickSearchEmployee frmQS = new frmQuickSearchEmployee(arr1);
                            frmQS.ShowDialog();
                            foreach (DataObjects.Employee oEmp in frmQS.arrResult)
                            {
                                arrResult.Add(oEmp);
                            }
                        }
                    }
                }

                ListViewItem item;
                int firstItem = 0;
                foreach (DataObjects.Employee oEmp in arrResult)
                {
                    if (!IsInListViewEmployee(oEmp))
                    {
                        item = new ListViewItem();
                        item.Text = oEmp.EmployeeId;
                        item.SubItems.Add(oEmp.LastName + " " + oEmp.FirstName);
                        lvwEmployee.Items.Add(item);
                        if (firstItem == 0)
                        {
                            item.Selected = true;
                        }
                        firstItem++;
                    }
                }
            }
        }

        private void lvwEmployee_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvwEmployee.SelectedItems.Count > 0)
            {
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(lvwEmployee.SelectedItems[0].Text);
                if (oEmp != null)
                {
                    FillData(oEmp);
                    LoadStatus(true, true, true, true);
                }
            }
            else
            {
                LoadStatus(true, false, true, true);
            }
        }

        private void trwOrg_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            SeleteNode = e.Node;
        }
        #endregion

        #region Execute
        public override void Add()
        {
            txtEmployeeId.Text = clsCommonFunc.RuleNumber5(boEmployee.GetMaxID() + 1);
            objMethod.ClearText(new Control[] { txtFirstName, txtLastName, txtAddressResident, txtAddressTemporary, txtPhoneHome, txtPhoneMobile, txtPhoneWork, txtPhoneExtension, txtEmailPersonal, txtEmailWork, txtImagePath, txtRemark, txtBankAccount });
            ClearColorTree(trwOrg.Nodes, Color.White);
            txtLastName.Focus();
        }

        public override void Delete()
        {
            try
            {
                if (txtEmployeeId.Text == "")
                    return;

                if (MessageBox.Show("Bạn có thực sự muốn xóa?", "Aquarius", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //Check Existing in table
                    //if (this.CheckExitToDelete(oDept.DEPT_CODE)) {
                    //    MessageBox.Show(".", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    return;
                    //}

                    //delete
                    boEmployee.DeleteByPK(txtEmployeeId.Text);
                    RemoveItem(txtEmployeeId.Text);
                    objMethod.ClearText(new Control[] { txtEmployeeId, txtFirstName, txtLastName, txtAddressResident, txtAddressTemporary, txtPhoneHome, txtPhoneMobile, txtPhoneWork, txtPhoneExtension, txtEmailPersonal, txtEmailWork, txtImagePath, txtRemark, txtBankAccount });
                    MessageBox.Show("Xóa nhân viên thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);                    
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void Save()
        {
            if (txtEmployeeId.Text == "")
            {
                return;
            }
            if (CheckValid())
            {
                try
                {
                    DataObjects.Employee oEmp = new DataObjects.Employee();
                    oEmp.EmployeeId = txtEmployeeId.Text;
                    oEmp.FirstName = txtFirstName.Text;
                    oEmp.LastName = txtLastName.Text;
                    oEmp.Gender = cboGender.SelectedValue != null ? cboGender.SelectedValue.ToString() : "";
                    oEmp.Nationality = cboNationality.SelectedValue != null ? cboNationality.SelectedValue.ToString() : "";
                    oEmp.Birthday = dtpBirthday.Value.Date;
                    oEmp.AddressResident = txtAddressResident.Text;
                    oEmp.AddressTemporary = txtAddressTemporary.Text;
                    oEmp.PhoneHome = txtPhoneHome.Text;
                    oEmp.PhoneMobile = txtPhoneMobile.Text;
                    oEmp.PhoneWork = txtPhoneWork.Text;
                    oEmp.PhoneExtension = txtPhoneExtension.Text;
                    oEmp.EmailPersonal = txtEmailPersonal.Text;
                    oEmp.EmailWork = txtEmailWork.Text;
                    oEmp.ImagePath = txtImagePath.Text;
                    DataObjects.Department oDept = (DataObjects.Department)SeleteNode.Tag;
                    oEmp.DepartmentId = oDept.DepartmentId;
                    oEmp.PositionId = cboPosition.SelectedValue != null ? cboPosition.SelectedValue.ToString() : "";
                    oEmp.Education = cboEducation.SelectedValue != null ? cboEducation.SelectedValue.ToString() : "";
                    oEmp.BankAccount = txtBankAccount.Text;
                    oEmp.BankCode = cboBank.SelectedValue != null ? cboBank.SelectedValue.ToString() : "";
                    oEmp.Remark = txtRemark.Text;
                    oEmp.Status = "CUR";

                    DataObjects.Employee oExistEmp = boEmployee.GetObjectByPK(oEmp.EmployeeId);
                    if (oExistEmp == null)
                    {
                        boEmployee.Insert(oEmp);
                        AddItem(oEmp);
                    }
                    else
                    {
                        boEmployee.Update(oEmp);
                        RemoveItem(oEmp.EmployeeId);
                        AddItem(oEmp);
                    }

                    MessageBox.Show("Cập nhật nhân viên thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + Environment.NewLine + "Không thể cập nhật nhân viên.", "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        public override void Find()
        {
            frmSearchEmployee frmSearch = new frmSearchEmployee();
            frmSearch.ShowDialog();

            ArrayList arrResult = frmSearch.arrResult;
            ListViewItem item;
            int firstItem = 0;

            foreach (DataObjects.Employee oEmp in arrResult)
            {
                if (!IsInListViewEmployee(oEmp))
                {
                    item = new ListViewItem();
                    item.Text = oEmp.EmployeeId;
                    item.SubItems.Add(oEmp.LastName + " " + oEmp.FirstName);
                    lvwEmployee.Items.Add(item);

                    if (firstItem == 0)
                    {
                        item.Selected = true;
                    }
                    firstItem++;
                }
            }
        }
        #endregion

        #region Method
        private void BuildTree()
        {
            Business.Department boDept = new Business.Department();
            trwOrg.Nodes.Clear();
            TreeNode treeNode;
            DataObjects.Department oDept;
            arrDept = boDept.GetListByStatus("CUR");
            ArrayList firstLevelNodes = GetChild();
            for (int i = 0; i <= firstLevelNodes.Count - 1; i++)
            {
                treeNode = BuildSubTree((DataObjects.Department)firstLevelNodes[i]);
                oDept = (DataObjects.Department)firstLevelNodes[i];
                treeNode.Tag = oDept;
                this.trwOrg.Nodes.Add(treeNode);
            }

            this.trwOrg.ImageIndex = 0;
            trwOrg.ExpandAll();
        }

        private TreeNode BuildSubTree(DataObjects.Department obj)
        {

            TreeNode treeNode = new TreeNode(Convert.ToString(obj.DepartmentName));
            ArrayList childArray = GetChild(obj.DepartmentId);
            TreeNode childNode = default(TreeNode);
            DataObjects.Department oDept;
            for (int i = 0; i <= childArray.Count - 1; i++)
            {
                childNode = BuildSubTree((DataObjects.Department)childArray[i]);
                oDept = (DataObjects.Department)childArray[i];
                childNode.Tag = oDept;
                treeNode.Nodes.Add(childNode);
            }
            return treeNode;

        }

        private ArrayList GetChild()
        {
            ArrayList arr = new ArrayList();
            arr = arrDept;
            ArrayList array = new ArrayList();
            foreach (DataObjects.Department obj in arr)
            {
                if (obj.ParentId == "-1")
                {
                    array.Add(obj);
                }
            }
            return array;

        }

        private ArrayList GetChild(string parentID)
        {
            ArrayList arr = new ArrayList();
            arr = arrDept;
            ArrayList array = new ArrayList();
            foreach (DataObjects.Department obj in arr)
            {
                if (obj.ParentId == parentID)
                {
                    array.Add(obj);
                }
            }
            return array;

        }

        private void GetListPosition()
        {
            try
            {
                Business.Position boPosition = new Business.Position();
                ArrayList arr = boPosition.List();
                cboPosition.DataSource = arr;
                cboPosition.ValueMember = "PositionId";
                cboPosition.DisplayMember = "PositionName";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool IsInListViewEmployee(DataObjects.Employee oEmp)
        {
            foreach (ListViewItem item in lvwEmployee.Items)
            {
                if (item.Text == oEmp.EmployeeId)
                {
                    return true;
                }
            }
            return false;
        }

        private void LoadStatusOnce()
        {
            exeCtrl.btnEdit.Enabled = false;
            exeCtrl.btnCancel.Enabled = false;
            exeCtrl.btnView.Enabled = false;
            exeCtrl.btnFunction.Enabled = false;
            exeCtrl.btnExport.Enabled = false;
            exeCtrl.btnSendmail.Enabled = false;
            exeCtrl.btnPrint.Enabled = false;

            exeCtrl.btnEdit.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnCancel.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnView.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnFunction.BackColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnExport.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnSendmail.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnPrint.ButtonColor = Color.FromArgb(171, 171, 171);

            exeCtrl.btnEdit.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnCancel.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnView.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnFunction.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnExport.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnSendmail.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnPrint.ForeColor = Color.FromArgb(241, 244, 251);
        }

        private void LoadStatus(bool blAdd, bool blDelete, bool blSave, bool blFind)
        {
            exeCtrl.btnAdd.Enabled = blAdd & bAdd;
            exeCtrl.btnDelete.Enabled = blDelete & bDelete;
            exeCtrl.btnSave.Enabled = blSave & bSave;
            exeCtrl.btnFind.Enabled = blFind & bFind;

            exeCtrl.btnAdd.ButtonColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnDelete.ButtonColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnSave.ButtonColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnFind.ButtonColor = exeCtrl.btnFind.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);

            exeCtrl.btnAdd.ForeColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnDelete.ForeColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnSave.ForeColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnFind.ForeColor = exeCtrl.btnFind.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
        }

        private void FillData(DataObjects.Employee oEmp)
        {
            try
            {
                txtEmployeeId.Text = oEmp.EmployeeId;
                txtLastName.Text = oEmp.LastName;
                txtFirstName.Text = oEmp.FirstName;
                if (oEmp.Gender != null && oEmp.Gender != "")
                    cboGender.SelectedValue = oEmp.Gender;
                if (oEmp.Nationality != null && oEmp.Nationality != "")
                    cboNationality.SelectedValue = oEmp.Nationality;
                dtpBirthday.Value = oEmp.Birthday.Value;
                txtAddressResident.Text = oEmp.AddressResident;
                txtAddressTemporary.Text = oEmp.AddressTemporary;
                txtPhoneHome.Text = oEmp.PhoneHome;
                txtPhoneMobile.Text = oEmp.PhoneMobile;
                txtPhoneWork.Text = oEmp.PhoneWork;
                txtPhoneExtension.Text = oEmp.PhoneExtension;
                txtEmailPersonal.Text = oEmp.EmailPersonal;
                txtEmailWork.Text = oEmp.EmailWork;
                txtImagePath.Text = oEmp.ImagePath;

                //department
                ClearColorTree(trwOrg.Nodes, Color.White);
                CurDept(trwOrg.Nodes, oEmp.DepartmentId);

                if (oEmp.PositionId != null && oEmp.PositionId != "")
                    cboPosition.SelectedValue = oEmp.PositionId;
                if (oEmp.Education != null && oEmp.Education != "")
                    cboEducation.SelectedValue = oEmp.Education;
                txtBankAccount.Text = oEmp.BankAccount;
                if (oEmp.BankCode != null && oEmp.BankCode != "")
                    cboBank.SelectedValue = oEmp.BankCode;
                txtRemark.Text = oEmp.Remark;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CurDept(TreeNodeCollection node, string deptid)
        {
            foreach (TreeNode n in node)
            {
                DataObjects.Department oDept = (DataObjects.Department)n.Tag;
                if (oDept.DepartmentId == deptid)
                {
                    n.BackColor = Color.Aqua;
                    curNode = n;
                    SeleteNode = curNode;
                    return;
                }
                CurDept(n.Nodes, deptid);
            }
        }

        private void ClearColorTree(TreeNodeCollection node, Color color)
        {
            foreach (TreeNode n in node)
            {
                n.BackColor = color;
                ClearColorTree(n.Nodes, color);
            }
        }

        private bool CheckValid()
        {
            if (txtLastName.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập họ.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtLastName.Focus();
                return false;
            }
            if (txtFirstName.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập tên.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtFirstName.Focus();
                return false;
            }
            if (txtEmailPersonal.Text.Trim().Length > 0)
            {
                if (!objMethod.CheckEmail(txtEmailPersonal.Text))
                {
                    MessageBox.Show("Email cá nhân không hợp lệ.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmailPersonal.Focus();
                    return false;
                }
            }
            if (txtEmailWork.Text.Trim().Length > 0)
            {
                if (!objMethod.CheckEmail(txtEmailWork.Text))
                {
                    MessageBox.Show("Email công ty không hợp lệ.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmailWork.Focus();
                    return false;
                }
            }
            if (SeleteNode == null)
            {
                MessageBox.Show("Vui lòng chọn phòng ban.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                trwOrg.Focus();
                return false;
            }
            return true;
        }

        private void AddItem(DataObjects.Employee oEmp)
        {
            ListViewItem item = new ListViewItem();
            item.Text = oEmp.EmployeeId;
            item.SubItems.Add(oEmp.LastName + " " + oEmp.FirstName);
            lvwEmployee.Items.Add(item);
        }

        private void RemoveItem(string empId)
        {
            foreach (ListViewItem item in lvwEmployee.Items)
            {
                if (item.Text == empId)
                {
                    lvwEmployee.Items.Remove(item);
                    return;
                }
            }
        }
        #endregion

        
    }
}
